package top.lingkang.authoritypro.config.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import top.lingkang.authoritypro.data.dto.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lingkang
 * Created by 2021/12/14
 */
public class LoginFialHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //让浏览器用utf8来解析返回的数据
        httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
        httpServletResponse.setCharacterEncoding("UTF-8");//防止中文乱码
        httpServletResponse.getWriter().write(
                JSON.toJSONString(new ResponseResult<>().fail(e.getMessage()))
        );
    }
}
